package cn.edu.zafu.bigdata.x.huangxihao202211080211;

import java.io.*;
import java.util.*;

public class RhymingWords11 {

    // 读取文件并找到押韵单词的方法
    public static List<String> findRhymingWords(String fileName, int rhymeLength) {
        List<String> words = new ArrayList<>();
        Map<String, List<String>> rhymeGroups = new HashMap<>();

        // 读取文件中的单词
        try (BufferedReader reader = new BufferedReader(new FileReader("files/" + fileName))) {
            String word;
            while ((word = reader.readLine()) != null) {
                words.add(word.trim());
            }
        } catch (IOException e) {
            System.out.println("读取文件时出错: " + e.getMessage());
        }

        // 根据押韵部分将单词分组
        for (String word : words) {
            if (word.length() >= rhymeLength) {
                String rhymePart = word.substring(word.length() - rhymeLength).toLowerCase();
                rhymeGroups.computeIfAbsent(rhymePart, k -> new ArrayList<>()).add(word);
            }
        }

        // 输出每组押韵单词
        List<String> rhymingWords = new ArrayList<>();
        for (List<String> group : rhymeGroups.values()) {
            if (group.size() > 1) { // 如果有多个押韵单词
                rhymingWords.addAll(group);
            }
        }

        return rhymingWords;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 提示用户输入押韵长度
        System.out.print("请输入押韵字母数（如 2 表示最后2个字母押韵）: ");
        int rhymeLength = scanner.nextInt();

        // 指定文件名
        String fileName = "words.txt";

        // 查找并显示押韵单词
        List<String> rhymingWords = findRhymingWords(fileName, rhymeLength);
        System.out.println("押韵的单词为:");
        for (String word : rhymingWords) {
            System.out.println(word);
        }
    }
}
